import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/custom_code_field_widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

/// @Author lixiaobin
/// @Date 2024/1/26
/// @Description 钱包输入密码
class AuthenticationPage extends StatefulWidget {
  final String setPassword; // setPassword = 1：设置密码，setPassword = 0: 密码验证
  const AuthenticationPage({required this.setPassword, super.key});

  @override
  State<AuthenticationPage> createState() => _AuthenticationPageState();
}

class _AuthenticationPageState extends State<AuthenticationPage> {
  // final _pwdArr = <String>[];
  // final _keyCount = 6;

  String _pasWord = '';

  @override
  Widget build(BuildContext context) {
    String naviTitle = widget.setPassword == "1" ? "设置密码" : "密码验证";
    return Scaffold(
        // appBar: CommWidget.getCommAppbar(context),
        appBar: CommWidget.getCommAppbar(context, title: naviTitle),
        body: Container(
          color: ColorRes.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // Container(
              //   height: 12.w,
              //   color: ColorRes.colorf5f5f5,
              // ),
              SizedBox(height: 50.w),
              Text(
                '请输入钱包密码',
                style: TextStyle(color: ColorRes.color333333, fontSize: 16.sp, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 30.w),

              Container(
                padding: EdgeInsets.only(left: 20.w, right: 20.w),
                child: CustomCodeFieldWidget(
                  onChanged: _handleCodeChanged, // 设置输入内容改变监听
                  obscureText: true, // 显示暗文
                ),
              ),

              SizedBox(height: 15.w),
              if (widget.setPassword != "1")
                Container(
                  alignment: Alignment.topRight,
                  margin: EdgeInsets.only(right: 20.w),
                  child: GestureDetector(
                    onTap: () {
                      // Log.d('忘记密码点击');
                      // Fluttertoast.showToast(msg: '忘记密码点击');
                      context.push(PageUrl.walletForgotPassword);
                    },
                    child: Text(
                      '忘记密码？',
                      style: TextStyle(color: ColorRes.colorA9A9A9, fontSize: 13.sp, fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              Container(
                margin: EdgeInsets.only(left: 20.w, top: 40.w, right: 20.w),
                child: CommWidget.customBuildBtn("确定", () {
                  submit();
                }, ColorRes.colorMain, ColorRes.colorB8B3FA, 6.w, isSelect: _pasWord.length == 6),
              ),
              Expanded(child: Container()),
              // Table(
              //   border: TableBorder.all(
              //     width: 0.5,
              //     color: ColorRes.color333333,
              //   ),
              //   children: [
              //     TableRow(
              //       children: [
              //         buildKey('1'),
              //         buildKey('2'),
              //         buildKey('3'),
              //       ],
              //     ),
              //     TableRow(
              //       children: [
              //         buildKey('4'),
              //         buildKey('5'),
              //         buildKey('6'),
              //       ],
              //     ),
              //     TableRow(
              //       children: [
              //         buildKey('7'),
              //         buildKey('8'),
              //         buildKey('9'),
              //       ],
              //     ),
              //     TableRow(
              //       children: [
              //         buildKey(''),
              //         buildKey('0'),
              //         buildDelKey(),
              //       ],
              //     )
              //   ],
              // )
            ],
          ),
        ));
  }

  void _handleCodeChanged(String code) {
    setState(() {
      _pasWord = code;
    });
    // 打印当前输入的内容
    print('Current code: $code');

    // 在这里调用你的接口，将输入的密码传递过去
    // yourApiCall(code);
  }

  // Widget buildKey(String keyNumber) {
  //   return InkWell(
  //       onTap: () {
  //         if ('' != keyNumber && _pwdArr.length < _keyCount) {
  //           _pwdArr.add(keyNumber);
  //           setState(() {});
  //         }
  //       },
  //       child: Container(
  //           alignment: Alignment.center,
  //           height: 60.w,
  //           child: Text(
  //             keyNumber,
  //             style: TextStyle(
  //               color: ColorRes.color333333,
  //               fontSize: 20.sp,
  //             ),
  //           )));
  // }

  // Widget buildDelKey() {
  //   return InkWell(
  //       onTap: () {
  //         _pwdArr.removeLast();
  //         setState(() {});
  //       },
  //       child: Container(
  //           alignment: Alignment.center,
  //           height: 60.w,
  //           child: ImageLoader.loadAsset('icon_keyboard_del.webp', 0, size: Size(40.w, 20.w))));
  // }

  // List<Widget> buildInputPwd() {
  //   var arr = <Widget>[];
  //   for (int i = 0; i < _keyCount; i++) {
  //     var isPwd = i < _pasWord.length;
  //     arr.add(Container(
  //       width: 45.w,
  //       height: 45.w,
  //       margin: EdgeInsets.only(right: i < _keyCount - 1 ? 10.w : 0.w),
  //       padding: EdgeInsets.zero,
  //       alignment: Alignment.center,
  //       decoration: BoxDecoration(
  //           borderRadius: BorderRadius.circular(5.w), border: Border.all(color: ColorRes.colord2d2d2, width: 0.5.w)),
  //       child: Visibility(
  //         visible: isPwd,
  //         child: ImageLoader.loadAsset('icon_point_star.webp', 30.w),
  //       ),
  //     ));
  //   }
  //   return arr;
  // }

  /// 提交数据
  submit() async {
    if (_pasWord.isEmpty) {
      Fluttertoast.showToast(msg: '请输入密码');
      return;
    }

    if (_pasWord.length < 6) {
      Fluttertoast.showToast(msg: '密码位数为6');
      return;
    }

    // setPassword = 1：设置密码，setPassword = 0: 密码验证
    if (widget.setPassword == "1") {
      _setWalletPwd();
    } else {
      //同意协议
      var user = App.instance.userInfo;
      var httpRequest = HttpRequest('${Api.walletAgree}/${user?.id ?? ''}', isShowLoading: false);
      await HttpClient.get(httpRequest);

      var pwdStr = _pasWord;
      // for (var element in _pwdArr) {
      //   pwdStr += element;
      // }

      //检查输入的密码
      var map = {'userMedicalId': user?.id, 'safeCode': StringUtils.dartMd5(pwdStr)};
      var request = HttpRequest(Api.checkSafePassword, body: map);
      var httpResponse = await HttpClient.post(request);
      var serviceResult = ServiceResult<String?>.simple(httpResponse);
      if (!serviceResult.success) {
        Fluttertoast.showToast(msg: serviceResult.responseMsg ?? '');
        return;
      }

      if (!mounted) return;
      context.pushReplacement(PageUrl.walletMain);
    }

    // //检查身份证照片是否上传
    // var response = await HttpClient.postJson(HttpRequest(Api.checkIdcardImg,
    //     body: {'doctorId': user?.id}, isShowLoading: false));
    // var result = ServiceResult<dynamic>.simple(response);
    // if (!result.success) {
    //   //补充证件照
    //   NativeInterface().openNativePage('auth_idCard_img', '');
    //   return;
    // }
  }

  /// 设置密码
  _setWalletPwd() async {
    if (_pasWord.length < 6) {
      ToastUtils.showToast(context, '请输入6位纯数字的安全码');
      return;
    }
    var id = App.instance.userInfo?.id;
    if (id == null || id.isEmpty == true) return;
    var httpRequest = HttpRequest(Api.walletSetPwd, urlParams: {
      "userMedicalId": id,
      'safeCode': StringUtils.dartMd5(_pasWord),
    });
    var httpResponse = await HttpClient.get(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    print("设置钱包密码httpResponse = ${httpResponse.body}");
    ToastUtils.showToast(context, serviceResult.responseMsg);
    if (serviceResult.success) {
      FocusScope.of(context).unfocus();
      context.pushReplacement(PageUrl.walletPwd);
    }
  }
}
